#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem << "  ";
    }
    cout << endl;
}

void printCapacity(const vector<int> &vec)
{
    cout << "size() = " << vec.size() << endl;
    cout << "capacity() = " << vec.capacity() << endl;
}

void test()
{
    cout << "sizeof(vector<int>) = " << sizeof(vector<int>) << endl;
    cout << "sizeof(vector<long>) = " << sizeof(vector<long>) << endl;
    vector<int> number = {1, 3, 5, 7, 9, 8, 6, 4, 2};
    display(number);
    printCapacity(number);

    cout << endl << "在vector的尾部进行插入与删除" << endl;
    number.push_back(10);
    number.push_back(20);
    display(number);
    printCapacity(number);
    number.pop_back();
    display(number);
    printCapacity(number);

    //获取vector中的第一个元素的首地址？
    &number;//error，不能得到vector的第一个元素的首地址
    &*number.begin();//ok,可以取第一个元素首地址
    &number[0];//ok(同上)
    int *pt = number.data();//ok

    cout << endl << "在vector的任意位置进行插入" << endl;
    vector<int>::iterator it = number.begin();
    ++it;
    ++it;
    cout << "*it = " << *it << endl;
    number.insert(it, 100);
    display(number);
    printCapacity(number);
    cout << "*it = " << *it << endl;

    cout << endl;
    //因为vector每次在进行insert插入元素的时候，不知道插入的元素的个数，
    //所以有可能在插入的时候，导致底层发生了扩容（回收老的空间），但是
    //迭代器还指向已经回收的空间，此时迭代器已经失效了
    //这就是迭代器失效的现象之一
    //解决方案：每次使用迭代器的时候，重新置位
    it = number.begin();
    ++it;
    ++it;
    cout << "*it = " << *it << endl;
    number.insert(it, 8, 666);
    display(number);
    printCapacity(number);
    cout << "*it = " << *it << endl;

    cout << endl;
    vector<int> vec = {11, 44, 55};
    it = number.begin();
    ++it;
    ++it;
    cout << "*it = " << *it << endl;
    number.insert(it, vec.begin(), vec.end());
    display(number);
    printCapacity(number);
    cout << "*it = " << *it << endl;

    cout << endl;
    it = number.begin();
    ++it;
    ++it;
    cout << "*it = " << *it << endl;
    number.insert(it, {777, 999, 888});
    display(number);
    printCapacity(number);
    cout << "*it = " << *it << endl;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}


